#!/usr/bin/env python

import logging
import os
import sys
from django.core import management
from django.utils import daemonize

def run_daemon():
    # Add the grandparent of this binary's path to the path, so that
    # django finds all of Streamux's bits and pieces.
    path = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                        '../..'))
    print path
    sys.path.insert(0, path)

    # Get Django to configure itself, so that we can use the Streamux
    # DB models to access the database.
    from streamux import settings
    management.setup_environ(settings)

    from streamux.daemon import importer, health

    # Configure logging and possibly background.
    if settings.DAEMON_NO_BACKGROUND:
        logging.basicConfig(
            filename=settings.DAEMON_LOGFILE, level=logging.DEBUG,
            format='%(asctime)s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M')
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(levelname)s: %(message)s')
        console.setFormatter(formatter)
        logging.getLogger('').addHandler(console)
        logging.info('Not backgrounding, debug output to stderr')
    else:
        logging.basicConfig(
            filename=settings.DAEMON_LOGFILE, level=logging.INFO,
            format='%(asctime)s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M')

        print 'Backgrounding...'
        daemonize.become_daemon()

        # Write the PID file so that external apps can track us.
        pidfile = open(settings.DAEMON_PIDFILE, 'w')
        pidfile.write(str(os.getpid()))
        pidfile.close()

        logging.info('Starting up')

    health.serve_health_thread()

    importer_service = importer.MusicImporter()
    importer_service.run()

    # Remove the pidfile if we were daemonized.
    if not settings.DAEMON_NO_BACKGROUND:
        os.remove(settings.DAEMON_PIDFILE)
    logging.info('Shutting down')

def main():
    try:
        run_daemon()
    except KeyboardInterrupt:
        print
    except SystemExit:
        pass
    except Exception, e:
        logging.critical('Daemon crashed')
        import traceback
        import StringIO
        tb = StringIO.StringIO()
        traceback.print_exc(file=tb)
        logging.critical(tb.getvalue())

if __name__ == '__main__':
    main()
